package com.zx.mobile.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.zx.map.dao.model.ActiveRedpacket;
import com.zx.map.dao.model.Redpacket;
import com.zx.map.service.ActiveRedpacketService;
import com.zx.map.service.OrdLogService;
import com.zx.map.service.RedpacketService;
import com.zx.map.service.model.MerchantInfoDetailModel;
import com.zx.map.service.model.OrdLogModel;
import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.ErrorMessages;
import com.zx.map.utils.SUConstants;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.mobile.utils.WebUtils;
import com.zx.platform.utils.AlipayUtil;
import com.zx.platform.utils.HttpClientCommon;

@Controller
@RequestMapping("/redpacket")
public class RedpacketController {

	private static Logger log = Logger.getLogger(RedpacketController.class);
	@Autowired
	private RedpacketService redpacketService;
	
	@Autowired
	private ActiveRedpacketService activeRedpacketService;
	
	
	public void send() {
		HttpClientCommon hcc = new HttpClientCommon();
		String s=hcc.getResultByGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx597f5f35a54abd5a&secret=5aee1cc2c8633e1bb5471090e8276505");
		JSONObject j=	JSONObject.parseObject(s);
		String json="{\r\n" + 
				"    \"touser\":\"ofttjxJ3PfxbUg84DBiBK6KgrSqY\",\r\n" + 
				"    \"msgtype\":\"news\",\r\n" + 
				"    \"news\":{\r\n" + 
				"        \"articles\": [\r\n" + 
				"         {\r\n" + 
				"             \"title\":\"Happy Day\",\r\n" + 
				"             \"description\":\"Is Really A Happy Day\",\r\n" + 
				"             \"url\":\"URL\",\r\n" + 
				"             \"picurl\":\"PIC_URL\"\r\n" + 
				"         },\r\n" + 
				"         {\r\n" + 
				"             \"title\":\"Happy Day\",\r\n" + 
				"             \"description\":\"Is Really A Happy Day\",\r\n" + 
				"             \"url\":\"URL\",\r\n" + 
				"             \"picurl\":\"PIC_URL\"\r\n" + 
				"         }\r\n" + 
				"         ]\r\n" + 
				"    }\r\n" + 
				"}";
		s=hcc.getResultByPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+j.get("access_token"),json);
	}
	
	@RequestMapping("/notice")
	@ResponseBody
	public Map notice(@RequestBody Redpacket redpacket, HttpServletRequest request) {
		try {
			HttpClientCommon hcc = new HttpClientCommon();
			hcc.getResultByGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx597f5f35a54abd5a&secret=5aee1cc2c8633e1bb5471090e8276505");
			
			send();
			return CommonResponseUtils.successResponse();
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
	
		
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Map add(@RequestBody Redpacket redpacket, HttpServletRequest request) {
		try {
			Objects.requireNonNull(redpacket);
			
			MerchantInfoDetailModel merchant = WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
			String merchantId = merchant.getMerchantId();
			Objects.requireNonNull(merchantId);
			redpacket.setMerchantId(merchantId);
			int result = redpacketService.add(redpacket);
			if(SUConstants.REDPACKET_IS_PROCESSING == result) {
				return CommonResponseUtils.failureResponse(ErrorMessages.MERCHANT_HAS_REDPACKET);
			}else if(SUConstants.ILLEGAL_DATE == result) {
				return CommonResponseUtils.failureResponse(ErrorMessages.ILLEGAL_DATE_MSG);
			}
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
		return CommonResponseUtils.successResponse();
		
	}
	/**
	 * 查询红包活动列表：status=1表示查询进行中的活动，status=2表示已经结束的活动
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/find")
	@ResponseBody
	public Map find(@RequestBody Map<String, Object> params, HttpServletRequest request) {
		
		try {
			MerchantInfoDetailModel merchant = WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
			String merchantId = merchant.getMerchantId();
			params = params.isEmpty() ? new HashMap<>() : params;
			params.put("merchantId", merchantId);
			List<Redpacket> redpacketList = redpacketService.queryByLimit(params);
			return CommonResponseUtils.successResponse(redpacketList);
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
		
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public Map del(@RequestBody Redpacket redpacket) {
		try {
			Objects.requireNonNull(redpacket);
			redpacketService.delete(redpacket.getRedpacketId());
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
		return CommonResponseUtils.successResponse();
	}
	/**
	 * 红包活动详细信息
	 * @param redpacket
	 * @return
	 */
	@RequestMapping("/info")
	@ResponseBody
	public Map info(@RequestBody Redpacket redpacket) {
		try {
			Objects.requireNonNull(redpacket);
			Redpacket info = redpacketService.info(redpacket.getRedpacketId());
			Map<String, Object> result = new HashMap<>();
			result.put("redpacket", info);
			return CommonResponseUtils.successResponse(result);
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public Map update(@RequestBody Redpacket redpacket) {
		try {
			Objects.requireNonNull(redpacket);
			redpacket.setUpdateDatetime(new Date());
			int result = redpacketService.update(redpacket);
			if(SUConstants.ILLEGAL_DATE == result) {
				return CommonResponseUtils.failureResponse(ErrorMessages.ILLEGAL_DATE_MSG);
			}
			return CommonResponseUtils.successResponse();
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
	}
	
	@RequestMapping("/sendRedpacket")
	@ResponseBody
	public Map sendRedpacket(@RequestBody Map<String, Object> params,  HttpServletRequest request) {
		
		try {
			Objects.requireNonNull(params);
			MobileUserDomain mUserDomain = WebUtils.queryCurrentLoginInfo(request);
			String merchantId = "abc";
			if (mUserDomain != null && mUserDomain.getMerchantInfoDetailModel() != null
					&& mUserDomain.getMerchantInfoDetailModel().getMerchantId() != null) {
				merchantId = mUserDomain.getMerchantInfoDetailModel().getMerchantId();
			}
			params.put("merchantId", merchantId);
			activeRedpacketService.sendRedpacket(params);
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
		
		return CommonResponseUtils.successResponse();
	}
	
	/**
	 * 判断当前商户是否已经有红包活动
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping("/hasActiveRedpacket")
	@ResponseBody
	public Map getActiveRedpacket(HttpServletRequest request) {
		try {
			MerchantInfoDetailModel merchant = WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
			String merchantId = merchant.getMerchantId();
			Objects.requireNonNull(merchantId);
			boolean hasActiveRedpacket = redpacketService.hasActiveRedpacket(merchantId);
			return CommonResponseUtils.successResponse(hasActiveRedpacket);
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
		
	}
	/**
	 * 使用红包的接口
	 * @return
	 */
	@RequestMapping("/useRedpacket")
	@ResponseBody
	public Map useRedpacket(@RequestBody Map<String, Object> params, HttpServletRequest request) {
		try {
			Objects.requireNonNull(params);
			MobileUserDomain mUserDomain = WebUtils.queryCurrentLoginInfo(request);
			String merchantId = "abc";
			if (mUserDomain != null && mUserDomain.getMerchantInfoDetailModel() != null
					&& mUserDomain.getMerchantInfoDetailModel().getMerchantId() != null) {
				merchantId = mUserDomain.getMerchantInfoDetailModel().getMerchantId();
			}
			params.put("merchantId", merchantId);
			redpacketService.dealRedpacketUsed(params);
			return CommonResponseUtils.successResponse();
		}catch(Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
		
	}
	
	@RequestMapping("/noticeInfo")
	@ResponseBody
	public Map noticeInfo(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		try {
			MerchantInfoDetailModel merchant = WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
			String merchantId = merchant.getMerchantId();
			Objects.requireNonNull(merchantId);
			Map<String, Object> result = redpacketService.noticeInfo(merchantId, Integer.parseInt((String)map.get("pageNum")), Integer.parseInt((String)map.get("pageSize")));
			return CommonResponseUtils.successResponse(result);
		}catch(Throwable e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
		
	}
	
	@RequestMapping("/getMoney")
	@ResponseBody
	public Map getMoney(@RequestBody Map<String, Object>map, HttpServletRequest request) {
		try {
			MerchantInfoDetailModel merchant = WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
			String merchantId = merchant.getMerchantId();
			Objects.requireNonNull(merchantId);
			BigDecimal result = BigDecimal.ZERO;
			if(!map.isEmpty() && map.containsKey("useMoney")) {
				result = redpacketService.getMoney(merchantId, new BigDecimal((String)map.get("useMoney")));
			}
			
			return CommonResponseUtils.successResponse(result);
		}catch(Throwable e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return CommonResponseUtils.failureResponse(e.getMessage());
		}
	}
	
	@Autowired
	private OrdLogService ordLogService;
	@RequestMapping("test")
	@ResponseBody
	public void dealRedpacket(@RequestBody OrdLogModel tempOrd) throws AlipayApiException, ParseException {
		BigDecimal paymentMoney = new BigDecimal(tempOrd.getPaymentAmt());
		//如果是支付宝，满足红包领取条件反现
		
		Map<String, Object> redAndActive = activeRedpacketService.getActiveRedpacketByUseMoney(tempOrd.getMerchantId(), tempOrd.getBgAccountId(), new BigDecimal(tempOrd.getPaymentAmt()));
		if(!redAndActive.isEmpty() && redAndActive.containsKey("redpacket") && redAndActive.containsKey("activeRedpacket")) {
			Redpacket redpacket = (Redpacket) redAndActive.get("redpacket");
			ActiveRedpacket activeRedpacket = (ActiveRedpacket) redAndActive.get("activeRedpacket");
			
			//订单金额大于满减要求且是支付宝支付，反现给支付宝
			if("1".equals(tempOrd.getPaymentType()) && paymentMoney.compareTo(redpacket.getUseMoney()) >= 0) {
				AlipayUtil.refundOrder(tempOrd.getOrdId(), redpacket.getMoney().toString());
				activeRedpacket.setIsUsed(true);
				activeRedpacket.setUsedDatetime(new Date());
				activeRedpacket.setOrdId(tempOrd.getOrdId());
				activeRedpacketService.update(activeRedpacket);
				//更新红包活动的信息
				int useNum = redpacket.getUseNum() + 1;
				redpacket.setUseNum(useNum);
				BigDecimal activeMoney = redpacket.getActiveMoney().add(paymentMoney);
				redpacket.setActiveMoney(activeMoney);
				
				redpacketService.update(redpacket);
				//修改订单金额
				tempOrd.setRedpacketRefund(redpacket.getMoney());
				ordLogService.update(tempOrd);
				paymentMoney = paymentMoney.subtract(redpacket.getMoney());
			}
		}
		//判断是否可以领取优惠券
		Map<String, Object> params = new HashMap<>();
		params.put("merchantId", tempOrd.getMerchantId());
		
		params.put("totalMoney", paymentMoney);
		params.put("userId", tempOrd.getBgAccountId());
		activeRedpacketService.sendRedpacket(params);
	}
}
